layui.use(['table', 'form', 'jquery', 'request', 'tool', 'pearOper'], function () {
    let table = layui.table;
    let form = layui.form;
    let $ = layui.jquery;
    let request = layui.request;
    let tool = layui.tool;
    var pearOper = layui.pearOper;
    var pickList = [], pageList = [], searchCount = 0, searchForm;
    let MODULE_PATH = "/admin/authorityApi/api";
    Init();

    function Init() {
        searchForm = $("#searchForm");
        table.render({
            elem: '#power-table',
            toolbar: '#power-toolbar',
            url: MODULE_PATH + '/list',
            skin: 'line',
            height: tool.getLayuiTableHeight(searchForm.height() * 2 + 60),
            method: 'post',
            contentType: "application/json",
            where: tool.serializeObject(searchForm),
            page: true,
            parseData: function (res) { //res 即为原始返回的数据
                $.each(res.data, function (index, item) {
                    if (pickList.indexOf(item.id) >= 0) {
                        //如果集合中有的话，给rows添加check属性选中
                        res.data[index]["LAY_CHECKED"] = true;
                    }
                })
                searchCount = res.count;
                return {
                    "code": res.code, //解析接口状态
                    "count": res.count, //解析数据长度
                    "data": res.data //解析数据列表
                };
            },
            done: function (res, curr, count) {
                pageList = [];
                $.each(res.data, function (index, item) {
                    pageList.push(item.id);
                })
                pickMsg();
            },
            cols: [
                [
                    {type: 'checkbox', cellMinWidth: 50, unresize: true},
                    {field: 'comment', width: '20%', unresize: true, title: '接口注释'},
                    {field: 'className', width: '30%', unresize: true, title: '接口类路径'},
                    {field: 'methodName', width: '10%', unresize: true, title: '接口方法名'},
                    {
                        title: '是否是API', width: '10%', unresize: true, templet: function (d) {
                            if (d.isApi == '1')
                                return "是";
                            else
                                return "不是";
                        }
                    },
                    {field: 'roleName', width: '15%', unresize: true, title: '授权角色'},
                    {title: '操作', templet: '#power-bar', align: 'center'}
                ]
            ]
        });
    }

    table.on('checkbox(power-table)', function (obj) {
        if (obj.checked) {
            if (obj.type === 'all') {//全选
                $.each(pageList, function (index, item) {
                    if (pickList.indexOf(item) === -1)
                        pickList.push(item);
                })
            } else {//选中
                if (pickList.indexOf(obj.data.id) === -1)
                    pickList.push(obj.data.id);
            }
        } else {
            if (obj.type === 'all') {//全取消
                $.each(pageList, function (index, item) {
                    var i = pickList.indexOf(item);
                    if (i !== -1)
                        pickList.splice(i, 1);
                })
            } else {//取消
                var i = pickList.indexOf(obj.data.id);
                if (i !== -1)
                    pickList.splice(i, 1);
            }
        }
        pickMsg();
    });

    table.on('tool(power-table)', function (obj) {
        switch (obj.event) {
            case "role":
                role(obj.data);
                break;
        }
    });


    table.on('toolbar(power-table)', function (obj) {
        switch (obj.event) {
            case "batch":
                if (searchCount > 0)
                    batchRole(false);
                else
                    tool.pear.error("当前查询0条数据无法操作");
                break;
            case "pickBatch":
                if (pickList.length > 0)
                    batchRole(true);
                else
                    tool.pear.error("请先选择接口");
                break;
            case "reload":
                request.post({
                    url: MODULE_PATH + '/reload'
                });
                break;
            case "search":
                Init();
                break;
        }
    });

    function pickMsg() {
        $("#pickMsg").text("查询出：" + searchCount + '条；已选择：' + pickList.length + '条');
    }

    function batchRole(pick) {
        layer.open({
            type: 2,
            title: pick ? '批量操作当前选择结果' : '批量操作当前查询结果',
            shade: 0.1,
            area: ['450px', '600px'],
            btn: ['提交'],
            content: '/admin/authority/pickList',
            yes: function (index, layero) {
                var iframeWin = window[layero.find('iframe')[0]['name']];
                var pickLists = iframeWin.pickList;
                var type = 2;
                if (iframeWin.getHeadx().switch == 'on')
                    type = 1;
                roleList = '';
                for (const key in pickLists) {
                    roleList += key + ',';
                }
                if (roleList !== '' && roleList != null) {
                    var list = roleList.split(",");
                    list.pop();
                    roleList = JSON.stringify(list);
                } else {
                    tool.pear.fail("请选择角色");
                    return false;
                }
                iframeWin.request.post({
                    url: MODULE_PATH + '/batchUpdate',
                    data: {
                        where: JSON.stringify(pick ? pickList : tool.serializeObject(searchForm)),
                        roleList: roleList,
                        type: type,
                        change: pick ? 'pick' : 'all'
                    }
                }, function (res) {
                    if (res.code === 0)
                        layer.close(index);
                });
            },
            success: function (layero, index) {
                var iframeWin = window[layero.find('iframe')[0]['name']];
                iframeWin.Init('', true);
            },
            end: function (layero, index) {
                Init();
            }
        });
    }

    function role(data) {
        layer.open({
            type: 2,
            title: '编辑接口权限角色',
            shade: 0.1,
            area: ['450px', '600px'],
            btn: ['提交'],
            content: '/admin/authority/pickList',
            yes: function (index, layero) {
                var iframeWin = window[layero.find('iframe')[0]['name']];
                var pickList = iframeWin.pickList;
                roleList = '';
                for (const key in pickList) {
                    roleList += key + ',';
                }
                if (roleList !== '' && roleList != null) {
                    var list = roleList.split(",");
                    list.pop();
                    roleList = JSON.stringify(list);
                } else
                    roleList = null;
                iframeWin.request.post({
                    url: MODULE_PATH + '/update',
                    data: {
                        id: data.id,
                        roleList: roleList
                    }
                }, function (res) {
                    if (res.code === 0)
                        layer.close(index);
                });
            },
            success: function (layero, index) {
                var iframeWin = window[layero.find('iframe')[0]['name']];
                iframeWin.Init(data.roleList);
            },
            end: function (layero, index) {
                Init();
            }
        });
    }

});